package com.hansming.bss.modules.sfc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hansming.bss.common.utils.IdGen;
import com.hansming.bss.common.utils.PropertiesLoader;
import com.hansming.bss.common.web.BaseController;
import com.hansming.bss.modules.sfc.entity.Contacts;
import com.hansming.bss.modules.sfc.entity.Customer;
import com.hansming.bss.modules.sfc.entity.CustomerScoreLog;
import com.hansming.bss.modules.sfc.entity.PcUser;
import com.hansming.bss.modules.sfc.service.ContactsService;
import com.hansming.bss.modules.sfc.service.CustomerScoreLogService;
import com.hansming.bss.modules.sfc.service.CustomerService;
import com.hansming.bss.modules.sfc.service.PcUserService;
import com.hansming.bss.modules.sfc.util.AccountsCheckUtil;
import com.hansming.bss.modules.sfc.util.CodeUtil;
import com.hansming.bss.modules.sfc.util.SmsSingleSender;
import com.hansming.bss.modules.sfc.util.SmsSingleSenderResult;

import freemarker.template.SimpleDate;

@Controller
@RequestMapping(value = "/meb")
public class PcLoginController extends BaseController{
		
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private PcUserService pcuserService;
	
	@Autowired
	private ContactsService contactsService;
	
	
	@Autowired
	private CustomerScoreLogService	customerscorelogService;
	/*
	 *  登陆接口
	 */
	@RequestMapping(value="/login")
	public void Pclogin(HttpServletRequest request, HttpServletResponse response,String phone,String code,String password,String scode){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        boolean result = true;
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String mcode = "1";								//返回前台的消息状态
			String msg = "登录成功！";
			HttpSession session = request.getSession();
			String tcode = (String)session.getAttribute("signcode");
			
//			if(!phone.equals("") || !email.equals("")){
//				String md5password = AccountsCheckUtil.encodeByMD5(password);
//				Customer user = customerService.login(phone, email, md5password);
//				//检测user是否为空
//				if(user!=null){
//					code = "2";
//					msg  =	"用户名或密码错误";
//				}else{
//					
//					
//				}			
//			}
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date now = new Date();
			if(scode.equalsIgnoreCase(tcode)){
			if(!"".equals(code) && code != null){
				String time = pcuserService.selectPcUserByPhone(phone, code);
				PcUser pcuser = pcuserService.selectPcUserByPhoneAndCode(phone, code);
				if(time != null || !"".equals(time)){					
					long datetimenum = sdf.parse(sdf.format(sdf.parse(time))).getTime();
					long nowtimenum = sdf.parse(sdf.format(now)).getTime();
					long minutes = (nowtimenum-datetimenum)/1000;
					if(minutes < 300){//此处原判定条件为minutes > 300
						if(pcuser != null){
							
							String userid = pcuser.getUserid();
							Customer user = customerService.get(userid);
							String token = pcuser.getToken();
							String username = user.getUsername();
							String nick = user.getNick();
							if(username != null && !"".equals(username)){
								session.setAttribute("username", username);
							}else if(nick != null && !"".equals(nick)){
								session.setAttribute("username", nick);
							}							
							session.setAttribute("token", token);
							
							msg = "手机登录成功！";
							//以上为登陆成功存入session信息
						}else{
							//以下当无账号的时候登陆直接注册登陆
							PcUser pcuser1 = new PcUser();
							String id = IdGen.uuid();
							String id2 = IdGen.uuid();
							pcuser1.setUserid(id2);
							pcuser1.setId(id);
							pcuser1.setPhone(phone);
							pcuser1.setPassword( AccountsCheckUtil.encodeByMD5(password));
							pcuser1.setDatetime(sdf.format(now));
							//生成一个随机的token
							String token = IdGen.uuid();
							pcuser1.setToken(token);
							if(password!= null && !password.equals("")){
								pcuser1.setPasswordflag("1");
							}else{
								pcuser1.setPasswordflag("0");
							}
							pcuserService.savepcuser(pcuser1);
							Customer customer = new Customer();
							customer.setId(id2);
							customer.setPcuserid(id);
							customer.setNick("用户"+CodeUtil.randomNumber(6));
							customer.setPhone(phone);
							
							customerService.savecustomer(customer);
							SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
							CustomerScoreLog csl = new CustomerScoreLog();
							csl.setDetail("新账号注册赠送积分");
							csl.setDatetime(dft.format(now));
							csl.setScore(1000);
							csl.setType("1");
							csl.setCustomer(customer);
							customerscorelogService.save(csl);
							session.setAttribute("token", token);
						}
					}else{
						mcode = "2";
						msg = "验证码已超时";
					}
				}
			}else if(!password.equals("")){
				password = AccountsCheckUtil.encodeByMD5(password);
				PcUser pcuser = pcuserService.selectPcUserByPhoneAndPassword(phone,password);
				
				if(pcuser != null){
					String userid = pcuser.getUserid();
					Customer user = customerService.get(userid);
					
					String token = pcuser.getToken();
					String username = user.getUsername();
					String nick = user.getNick();
					if(username != null && !"".equals(username)){
						session.setAttribute("username", username);
					}else if(nick != null && !"".equals(nick)){
						session.setAttribute("username", nick);
					}	
					session.setAttribute("token", token);
					msg = "登录成功！";
				}else{
					
					mcode = "2";
					msg = "用户名或密码错误";
				}
			}
			}else{
				mcode = "2";
				msg = "图片验证码错误";
			}
			jsonObject.put("code",mcode);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	//检查是否登陆
	@RequestMapping(value="/checklogin")
	public void checkLogin(HttpServletRequest request,HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
     			PrintWriter out = response.getWriter();
     			JSONObject jsonObject = new JSONObject(); 
     	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
     	        String code = "1";
     	        String msg = "已登陆";
     	        HttpSession session = request.getSession();
     	        String token =  (String)session.getAttribute("token");
     	        if(!"".equals(token) && token!= null){
     	        	Customer customer = customerService.selectbypcusertoken(token);
     	        	if(customer != null) {
     	        		JSONObject object = new JSONObject();
     	        		object.put("name", customer.getNick());
     	        		datas.put(object);
     	        	}else {
     	        		code = "2";
         	        	msg ="未登录";
     	        	}
     	        }else{
     	        	code = "2";
     	        	msg ="未登录";
     	        }
     			jsonObject.put("code",code);
     			jsonObject.put("msg", msg);
     			jsonObject.put("data",datas);
     			out.print(jsonObject.toString());
     			out.flush();
     			out.close();
     		} catch (Exception e) {
     			// TODO Auto-generated catch block
     			e.printStackTrace();
     		}
	}
	
		@RequestMapping(value="/rem")
		public void remmebpassword(HttpServletRequest request,HttpServletResponse response){
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			 try {
					PrintWriter out = response.getWriter();
					JSONObject jsonObject = new JSONObject(); 
			        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
					String code = "1";										//返回前台的消息状态
					String msg = "xxxxxx";
					
					
					
					
					
					jsonObject.put("code",code);
					jsonObject.put("msg", msg);
					jsonObject.put("data",datas);
					out.print(jsonObject.toString());
					out.flush();
					out.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	
	/*
	 * 注册
	 */
	
	
	//检查手机是否重复
	@RequestMapping(value="/checkphone")
	public void checkphone(HttpServletRequest request, HttpServletResponse response,String phone){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";										//返回前台的消息状态
			String msg = "帐号可用";
			int result = customerService.checkphone(phone);
			if(result > 0){
				code = "2";
				msg = "该手机已被注册";
			}
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//发送图片验证码
	@RequestMapping(value="/codeimg")
	public void createcodeimage(HttpServletRequest request, HttpServletResponse response){
		try {
			//创建验证码图片
			CodeUtil.createcodeimage(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	//检测图片验证码
	@RequestMapping(value="/checkcode")
	public void checkimgcode(HttpServletRequest request, HttpServletResponse response,String code) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		JSONObject jsonObject = new JSONObject(); 
		String mcode = "1";
		String msg	= "验证码正确";
		HttpSession session = request.getSession();
		String signcode = (String)session.getAttribute("signcode");
		if(code.equalsIgnoreCase(signcode)){
			mcode = "1";
			msg	= "验证码正确";
		}else{
			mcode = "2";
			msg = "验证码错误";
		}
		jsonObject.put("code",mcode);
		jsonObject.put("msg", msg);
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
	//发送手机验证码
	@RequestMapping(value="/phonecode")
	public void sendphonecode(HttpServletRequest request, HttpServletResponse response,String phone){
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");//有些浏览器会报错xml解析错误 格式不佳位置，此设置可解决
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String mcode = "1";								//返回前台的消息状态
			String msg = "手机验证码发送成功！";	
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date now = new Date();
					PropertiesLoader config = new PropertiesLoader("config.properties");
					int appid = config.getInteger("phonemsgappid");
					String appkey = config.getProperty("phonemsgappkey");
					SmsSingleSender msgSender = new SmsSingleSender(appid, appkey);
					String nationCode = "86";
					String phoneNumber = phone;
					int templId = 68012;
					ArrayList<String> params = new ArrayList<String>();
					String ycode = CodeUtil.randomNumber(6);
					params.add(ycode);
					String sign = "搜房车";
					String extend = "";
					String ext = "";
					SmsSingleSenderResult result = msgSender.sendWithParam(nationCode, phoneNumber, templId, params, sign, extend, ext);
					
					String codetime = sdf.format(now);
					if(result.result == 0){
						int num = pcuserService.checkcodephone(phone);
						if(num == 0){
							//在sfc_phone_code表中储存手机号码和手机验证码
							pcuserService.savephonecode(phone, ycode, codetime);
						}else{
							//在sfc_phone_code表中更新手机号码和手机验证码
							pcuserService.updatephonecode(phone, ycode, codetime);
						}
					}else{
						mcode = "2";
						msg = "手机验证码发送失败！";
					}
			jsonObject.put("code",mcode);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	//验证手机验证码
	@RequestMapping(value="/checkphonecode")
	public void checkphonecode(HttpServletRequest request, HttpServletResponse response,String phone,String code){
		response.setCharacterEncoding("UTF-8");
		 response.setHeader("Cache-Control", "no-cache");	
		 try {
				PrintWriter out = response.getWriter();
				JSONObject jsonObject = new JSONObject(); 
		        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
				String mcode = "1";								//返回前台的消息状态
				String msg = "验证通过";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date now = new Date();
				String time = pcuserService.selectPcUserByPhone(phone, code);
					if(time != null || !time.equals("")  ){ 
						long datetimenum = sdf.parse(sdf.format(sdf.parse(time))).getTime();
						long nowtimenum = sdf.parse(sdf.format(now)).getTime();
						long minutes = (nowtimenum-datetimenum)/1000 ;
						if(minutes<300){
							
						}else{
							mcode ="2";
							msg = "验证超时";
						}
					}else{
						mcode = "2";
						msg =" 验证码错误";
					}
				jsonObject.put("code",mcode);
				jsonObject.put("msg", msg);
				jsonObject.put("data",datas);
				out.print(jsonObject.toString());
				out.flush();
				out.close();
		 }catch(Exception e){
			 e.printStackTrace();
		 }
	}
	
	//修改密码
	@RequestMapping(value="/repassword")
	public void updatePcUserPassWord(HttpServletRequest request, HttpServletResponse response,String phone,String password){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		try{
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject();  
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
	        String mcode = "1";								//返回前台的消息状态
	        String msg ="修改成功";
	        password = AccountsCheckUtil.encodeByMD5(password);
	        int result = pcuserService.updatepassworedbyphone(phone, password);
	        if(result != 1){
	        	mcode = "2";
	        	msg = "修改失败";
	        }   
	        jsonObject.put("code",mcode);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/register")
	public void register(HttpServletRequest request, HttpServletResponse response,String phone,String password,String code,String scode) throws ParseException, IOException{
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
      
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String mcode = "1";								//返回前台的消息状态
			String msg = "注册成功";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date now = new Date();
			
			String time = pcuserService.selectPcUserByPhone(phone, code);
			if(time != null && !time.equals("")  ){ 
				long datetimenum = sdf.parse(sdf.format(sdf.parse(time))).getTime();
				long nowtimenum = sdf.parse(sdf.format(now)).getTime();
				long minutes = (nowtimenum-datetimenum)/(1000 * 60);
				if(minutes >= 5){
					code = "2";
					msg = "验证码已超时";
				}else{
					PcUser pcuser = new PcUser();
					String id = IdGen.uuid();
					String id2 = IdGen.uuid();
					pcuser.setUserid(id2);
					pcuser.setId(id);
					pcuser.setPhone(phone);
					pcuser.setPassword( AccountsCheckUtil.encodeByMD5(password));
					pcuser.setDatetime(sdf.format(now));
					//生成一个随机的token
					String token = IdGen.uuid();
					pcuser.setToken(token);
					if(password!= null && !password.equals("")){
						pcuser.setPasswordflag("1");
					}else{
						pcuser.setPasswordflag("0");
					}
					pcuserService.savepcuser(pcuser);
					Customer customer = new Customer();
					customer.setId(id2);
					customer.setPcuserid(id);
					customer.setNick("用户"+CodeUtil.randomNumber(6));
					customer.setPhone(phone);
					
					customerService.savecustomer(customer);
					SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
					CustomerScoreLog csl = new CustomerScoreLog();
					csl.setDetail("新账号注册赠送积分");
					csl.setDatetime(dft.format(now));
					csl.setScore(1000);
					csl.setType("1");
					csl.setCustomer(customer);
					customerscorelogService.save(csl);
					HttpSession session = request.getSession();
					session.setAttribute("token", token);
				}
			}else{
				mcode = "2";
				msg = "验证码错误";
			}
			
			//****需要修改
//			Customer user = new Customer();
//			user.setPhone(account);
//			if(!password.equals("")){
//				user.setPassword(password);
//			}
//			customerService.save(user);
			
			
			jsonObject.put("code",mcode);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		
	}
	
	
	@RequestMapping(value="/checkemail")
	public void checkemail(HttpServletRequest request, HttpServletResponse response,String email){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "帐号可用";
			int result = customerService.checkemail(email);
			if(result > 0){
				code = "2";
				msg = "该邮箱已被注册";
			}
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	
	
	@RequestMapping(value="/qlogin")
	public void quickLogin(HttpServletRequest request, HttpServletResponse response,String phone){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "登录成功";		
			HttpSession session = request.getSession();
			
			
			
			
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
//获得联系人信息(暂时修改个根据用户固定id
	@RequestMapping(value="/getcontact")
	public void getcontactsinfo(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "访问成功";		
			HttpSession session = request.getSession();
			String token = (String)session.getAttribute("token");
			if(!token.equals("")){
				Customer customer = customerService.selectbypcusertoken(token);
				if(customer != null){
//				List<Contacts> contacts = contactsService.getContactsByuserId("d69b39013b754b848f56ef8d49b5af4e");
					List<Contacts> contacts = contactsService.getContactsByuserId(customer.getId());
					if(contacts != null){
						for(Contacts c:contacts){
							JSONObject obj = new JSONObject();
							obj.put("id", c.getId());
							obj.put("name", c.getCname());
							obj.put("identtype", c.getIdenttype());
							obj.put("identnum", c.getIdentnum());
							obj.put("email", c.getEmail());
							obj.put("phone", c.getPhone());
							datas.put(obj);
						}
					}else{
						code = "2";
						msg = "联系人信息为空";
					}
				}
        else{
					code = "2";
					msg = "获得用户信息失败";
				}
			}        else{
				code ="2";
				msg ="用户登陆信息出错";
			}
			
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/getcontactinfo")
	public void getcontactsdetailinfo(HttpServletRequest request, HttpServletResponse response,String id){
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "访问成功";		
			Contacts c = contactsService.get(id);
			JSONObject obj = new JSONObject();
			obj.put("name", c.getCname());
			obj.put("identtype", c.getIdenttype());
			obj.put("identnum", c.getIdentnum());
			obj.put("email", c.getEmail());
			obj.put("phone", c.getPhone());
			datas.put(obj);
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			System.out.println("---------------------------");
			System.out.println("name="+c.getCname());
			System.out.println("identtype="+c.getIdenttype());
			System.out.println("identnum="+c.getIdentnum());
			System.out.println("email="+c.getEmail());
			System.out.println("phone="+c.getPhone());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value="/loginout")
	public void loginout(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		session.removeAttribute("token");
		session.removeAttribute("username");
	}
}
